<!-- 代表作：公厕 -->
<script setup>
import { reactive, ref, watch, onMounted, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { loadUnitPosition, loadBMapGLScript, getMaskOverlay } from '@T2/utils/BMapGL_API.ts';
import { warnApi } from '@T2/service/api.ts';
import { getUnitsParams } from '@T2/utils/params.ts';
import { mapStyle } from './mapStyle.js';
import { isJSON } from '@T2/utils/utils.ts';
import NormalPNG from '@T2/assets/maps/buoy-normal.png';
import dayjs from 'dayjs';
import NumsBox from './framework/numsBox.vue';
import Charts from './framework/charts.vue';
import Units from './framework/units.vue';

const clickHandlers = [];
let maps = {};
const Resd = reactive({
  units: undefined,
  sensors: [],
});
onMounted(async () => {
  if (!window.BMapGL) {
    await loadBMapGLScript();
  }
  const { unitList, curIds } = await getUnitsParams('/P/Display/home02');
  Resd.units = unitList.filter(i => +i.x && +i.y).sort((a, b) => a.name.localeCompare(b.name, 'zh'));
  
  const warnList = await getWarnList();
  curIds.forEach(j => {
    const obj = warnList.find(i => i.sensor === j.s);
    j.state = obj ? false : true;
  });
  
  Resd.units.forEach(unit => {
    if (!isJSON(unit.params)) {
      return;
    }
    const paramsObj = JSON.parse(unit.params);
    const { others } = paramsObj || {};
    if (!others || others.length < 1 || !others[1].c?.length) {
      return;
    }
    unit._others = others[1].c[0];
  });
  const flag = true;
  // const flag = import.meta.env.MODE !== 'development';
  setTimeout(() => {
    flag && mapsInit();
  }, 500)
})
const getWarnList = () => {
  return new Promise((resolve, reject) => {
    warnApi({
      method: 'get',
      params: {
        page: 1,
        reset_time__isnull: true,
      }
    }).then(res => {
      resolve(res.results || []);
    }).catch(res => {
      reject([]);
    });
  });
}
const mapsInit = () => {
  if (!Resd.units.length) {
    ElMessage.error('未查询到设置了经纬度的站点！');
    return;
  }
  maps = new window.BMapGL.Map('map_container', { minZoom: 10 });
  maps.setMapStyleV2({styleJson: mapStyle});
  maps.setTilt(0);    // 设置地图倾斜角
  maps.setHeading(0); // 设置地图倾斜角
  maps.enableKeyboard();
  maps.enableScrollWheelZoom();
  maps.enableInertialDragging();
  maps.enableContinuousZoom();
  maps.setDisplayOptions({ poi: true, poiIcon: false});
  // getMaskOverlay('上海市', 1).then(res => {
  //   res?.mapmasks?.forEach(i => maps.addOverlay(i));
  //   res?.borders?.forEach(i => maps.addOverlay(i));
  // });
  
  /* viewPort: { center: {lat: 31.13, lng: 121.1}, zoom: 12 } */
  const points = Resd.units.map(i => new window.BMapGL.Point(+i.x, +i.y));
  const viewPort = maps.getViewport(points);
  // maps.centerAndZoom(viewPort.center, viewPort.zoom > 12 ? 12 : viewPort.zoom);
  maps.centerAndZoom(viewPort.center, viewPort.zoom);
  
  initHome(maps.getCenter(), maps.getZoom());
  
  const icon = new window.BMapGL.Icon(NormalPNG, new window.BMapGL.Size(0, 0));
  Resd.units.forEach(item => {
    const clickHandler = function(e) {
      openInfoWindow(item);
    };
    let marker = new window.BMapGL.Marker(new window.BMapGL.Point(+item.x, +item.y), { icon: icon });
    maps.addOverlay(drawMarker(marker, item));
    marker.addEventListener('click', clickHandler);
    clickHandlers.push({ marker, clickHandler });
  });
}
onBeforeUnmount(() => {
  clickHandlers.forEach(({ marker, clickHandler }) => {
    marker.removeEventListener('click', clickHandler);
  });
});
const drawMarker = (marker, item) => {
  setTimeout(() => {
    let eleIcon = document.createElement('div');
    eleIcon.className = item.warn_number > 0 ? 'map-buoy alarm' : 'map-buoy';
    marker.domElement.appendChild(eleIcon);
  }, 500);
  return marker;
}

/* 点击marker弹窗 */
const detail = reactive({
  data: null,
  dom: null,
});
const openInfoWindow = (item) => {
  const point = new window.BMapGL.Point(+item.x, +item.y);
  const content = `<div class="openTips" id="tipsUnitID${ item.id }"></div>`;
  const infoWindow = new window.BMapGL.InfoWindow(content, {
    width: 0,
    offset: new window.BMapGL.Size(-29, 0), //默认的一个引导箭头,宽58px,高31px,往左偏移一半宽度
  });
  maps.openInfoWindow(infoWindow, point);
  setTimeout(() => {
    detail.dom = document.getElementById(`tipsUnitID${ item.id }`);
  }, 50);
  detail.data = item;
}
const closeInfoWindow = () => {
  maps.closeInfoWindow();
}

/* 回到初始地图位置 */
const homeRt = reactive({
  times: 0,
  center: {},
  zoom: 12,
});
const initHome = (center, zoom) => {
  homeRt.center = center;
  homeRt.zoom = zoom;
}
watch(() => homeRt.times, (nv, ov) => {
  maps.centerAndZoom(homeRt.center, homeRt.zoom);
});
</script>

<template>
  <div id="map_container" class="BMap_container"></div>
  
  <template v-if="Resd.units">
    <div class="left">
      <NumsBox :units="Resd.units" />
      <Charts :units="Resd.units" />
    </div>
    
    <div class="right">
      <Units :units="Resd.units" />
    </div>
  </template>
  
  <teleport :to="detail.dom" v-if="detail.dom && detail.data">
    <div class="popup flex-column">
      <div class="header flex--center">
        <span>{{ detail.data.name }}</span>
        <el-icon class="close-icon" @click="closeInfoWindow()"><Close /></el-icon>
      </div>
      <img :src="'https://hengji.ieieye.com/' + detail.data._others.v" v-if="detail.data?._others?.v" />
      <div class="info flex">
        <label>环境评价：</label>
        <p>
          <span style="color: #FF0000;" v-if="detail.data.warn_number">差</span>
          <span style="color: #00FF40;" v-else>优</span>
        </p>
      </div>
      <div class="info flex">
        <label>当前温度：</label>
        <p>22℃</p>
      </div>
      <div class="info flex">
        <label>当前湿度：</label>
        <p>50%</p>
      </div>
      <div class="info flex">
        <label>公厕位置：</label>
        <p>{{ detail.data.addr }}</p>
      </div>
    </div>
  </teleport>
</template>

<style lang="scss" scoped>
@use '@T2/styles/BMap.scss';
.BMap_container {
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.5);
}
.popup {
  width: 100%;
  height: 100%;
  overflow: hidden;
  padding: 0 8px;
  .header {
    height: 50px;
    font-weight: 500;
    font-size: 16px;
    color: #FFFFFF;
    .close-icon {
      margin-left: auto;
      width: 30px;
      height: 30px;
      cursor: pointer;
    }
  }
  img {
    width: 100%;
    height: 168px;
    margin-bottom: 4px;
  }
  .info {
    margin-top: 8px;
    label {
      font-weight: 400;
      font-size: 14px;
      color: rgba(255,255,255,0.65);
      white-space: nowrap;
    }
    p {
      font-weight: 400;
      font-size: 14px;
      color: #FFFFFF;
    }
  }
}

.left {
  position: absolute;
  top: 50%;
  left: 20px;
  transform: translateY(-50%);
  display: grid;
  gap: 15px;
  grid-template-rows: 1fr 1fr;
  z-index: 1000;
}
.right {
  position: absolute;
  top: 50%;
  right: 20px;
  transform: translateY(-50%);
  z-index: 1000;
}
</style>

<style scoped>
:deep(.BMap_bubble_pop) {
  /* BMap_bubble_top高度为31px,img高度31px，50px为图标高度 */
  transform: translateY(calc(31px + 31px - 50px));
}
:deep(.map-buoy) {
  position: absolute;
  transform: translateX(-50%) translateY(-50px);
  width: 50px;
  height: 50px;
  background: url('@T2/assets/maps/toilet1.png') no-repeat center;
  background-size: 100% 100%;
}
:deep(.map-buoy.alarm) {
  background: url('@T2/assets/maps/toilet1-warn.png') no-repeat center;
  background-size: 100% 100%;
}
:deep(.openTips) {
  pointer-events: auto !important;
  overflow: hidden;
  z-index: 1000;
  width: 264px;
  height: 380px;
  background: url('./assets/popup-bg.png') no-repeat center;
  background-size: 100% 100%;
}
</style>